import React, { useEffect } from "react";
import { Modal, Form, Input, message, Button, Select } from "antd";
const { Option } = Select;

interface ProductValues {
  product_name: string;
  category_id: number;
}
 
interface ProductModalProps {
  title: string;
  visible: boolean;
  onCancel: () => void;
  onOk: (values: any) => void;
  defaultValue: any;
  categoryList: any[];
}

const ProductModal: React.FC<ProductModalProps> = ({
  title,
  visible,
  onCancel,
  onOk,
  defaultValue,
  categoryList = [],
}) => {
  const [form] = Form.useForm<ProductValues>();

  useEffect(() => {
    if (Object.keys(defaultValue).length === 0) {
      form.resetFields();
    } else {
      form.setFieldsValue({
        ...defaultValue,
      });
    }
  }, [defaultValue, visible]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      onOk(values);
      form.resetFields();
    } catch (errorInfo) {
      console.log("Failed:", errorInfo);
    }
  };

  return (
    <Modal
      title={title}
      visible={visible}
      onOk={handleOk}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="ok" type="primary" onClick={handleOk}>
          确定
        </Button>,
      ]}
    >
      <Form form={form}>
        <Form.Item
          label="物品名称"
          name="product_name"
          rules={[
            {
              required: true,
              whitespace: true,
              message: "请输入物品名称",
            },
          ]}
          validateTrigger="onBlur"
        >
          <Input placeholder="请输入物品名称" />
        </Form.Item>
        {/* <Form.Item
          label="库存数量"
          name="inventory"
          rules={[
            {
              required: true,
              type: "number",
              message: "请输入有效的库存数量",
            },
          ]}
          validateTrigger="onBlur"
        >
          <Input type="number" placeholder="请输入库存数量" />
        </Form.Item>
        <Form.Item
          label="提醒阈值"
          name="reminder_threshold"
          rules={[
            {
              required: true,
              type: "number",
              message: "请输入有效的提醒阈值",
            },
          ]}
          validateTrigger="onBlur"
        >
          <Input type="number" placeholder="请输入提醒阈值" />
        </Form.Item> */}

        <Form.Item
          label="种类"
          name="category_id"
          rules={[
            {
              required: true,
              message: "请选择用户角色",
            },
          ]}
        >
          <Select placeholder="输入种类" allowClear>
            {categoryList.map((ele: any) => (
              <Option key={ele.id} value={ele.id}>
                {ele.category_name}
              </Option>
            ))}
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ProductModal;
